<template>
    <div class="app-container">

        <div class="app-container-left">
            <tree ref="tree" @set-tree-data="setTreeData" @go_menu="go_menu" />
        </div>

        <div class="app-container-right">

            <div :class="['filter-container',{'open':formState}]">
                <a v-if="screenState" class="form-more" href="#" title="更多筛选" @click="formState = !formState"><i
                        :class="formState ? 'el-icon-caret-top':'el-icon-caret-bottom'" /></a>
                <!-- <el-form ref="form" :model="form" @keyup.enter.native="handleFilter()" label-width="80px"> -->

                <!-- 筛选框需要些双份 一种是没有展开状态下的  只有主要的几个筛选框，另一种是全部的筛选框都展示 也就是展开状态下的 -->
                <!-- 没有展开状态下的筛选框 -->
                <el-form v-if="!formState" ref="filtrateForm" :inline="true" :model="filtrateForm" label-width="80px">
                    <el-form-item label="房屋名称">
                        <el-input v-model.trim="filtrateForm.name" placeholder="请输入" style="width:160px;" clearable />
                    </el-form-item>
                    <!-- <el-form-item label="房屋状态">
                        <el-select v-model="filtrateForm.house_state" placeholder="请选择">
                            <el-option v-for="item in houseState_" :key="item.value" :label="item.lable" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="房屋功能">
                        <el-select v-model="filtrateForm.house_function" placeholder="请选择">
                            <el-option v-for="item in houseFunction_" :key="item.value" :label="item.lable" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item> -->

                    <el-form-item v-if="!formState">
                        <el-button class="filter-item" @click="handleFilter">
                            查询
                        </el-button>
                        <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                            @click="handleCreateHouse">新增房屋</el-button>
                        <el-button :loading="downloadLoading1" style="margin-left: 10px;" class="filter-item" type="primary"
                            @click="handleDownloadMock">
                            下载模板
                        </el-button>
                        <el-upload class="upload-demo" style="margin-left: 10px;" :headers="headers" :show-file-list="false"
                            :action="action" :on-success="handleSuccess" multiple :limit="1" name="file">
                            <el-button type="primary">导入</el-button>
                        </el-upload>
                        <el-button :loading="downloadLoading" style="margin-left: 10px;" class="filter-item" type="primary"
                            @click="handleDownload">
                            导出
                        </el-button>
                    </el-form-item>
                </el-form>

                <!-- 展开状态下的筛选框 -->
                <el-form v-if="formState" ref="form" :inline="true" :model="filtrateForm" label-width="80px">
                    <el-form-item label="房屋名称">
                        <el-input v-model.trim="filtrateForm.name" placeholder="请输入" style="width:160px;" clearable />
                    </el-form-item>
                    <el-form-item label="房屋状态">
                        <el-select v-model="filtrateForm.house_state" placeholder="请选择">
                            <el-option v-for="item in houseState_" :key="item.value" :label="item.lable" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="房屋功能">
                        <el-select v-model="filtrateForm.house_function" placeholder="请选择">
                            <el-option v-for="item in houseFunction_" :key="item.value" :label="item.lable" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>

                </el-form>
                <div v-if="formState" class="filter-button">
                    <el-button class="filter-item" @click="handleFilter">
                        查询
                    </el-button>
                    <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                        @click="handleCreateHouse">新增房屋</el-button>
                    <el-button :loading="downloadLoading1" style="margin-left: 10px;" class="filter-item" type="primary"
                        @click="handleDownloadMock">
                        下载模板
                    </el-button>
                    <el-upload class="upload-demo" style="margin-left: 10px;" :headers="headers" :show-file-list="false" :action="action"
                        :on-success="handleSuccess" multiple :limit="1" name="file">
                        <el-button type="primary">导入</el-button>
                    </el-upload>
                    <el-button :loading="downloadLoading" style="margin-left: 10px;" class="filter-item" type="primary"
                        @click="handleDownload">
                        导出
                    </el-button>
                </div>

            </div>

            <div :class="['table',{'open':formState}]">
                <div class="table-container">
                    <el-table :key="tableKey" v-loading="listLoading" row-key="menuId" height="100%" :data="list" border fit
                        highlight-current-row style="width: 100%;" @selection-change="selectionChangeHandle">

                        <el-table-column type="selection" header-align="center" align="center" width="50" />

                        <el-table-column prop="name" header-align="center" align="center" label="房屋名称" width="180">
                            <template
                                slot-scope="scope">{{scope.row.buildingName}}-{{scope.row.unitName}}-{{scope.row.floorName}}-{{scope.row.name}}</template>
                        </el-table-column>
                        <el-table-column prop="type" header-align="center" align="center" label="房屋功能" />
                        <el-table-column prop="area" header-align="center" align="center" label="面积(m²)" />
                        <el-table-column prop="state" header-align="center" align="center" label="房屋状态">
                            <template slot-scope="scope">{{ scope.row.state | houseStateFilter  }}</template>
                        </el-table-column>
                        <!-- <el-table-column prop="customerName" header-align="center" align="center" label="客户姓名" /> -->
                        <el-table-column prop="updateTime" header-align="center" align="center" width="180" label="最后编辑时间">
                            <template slot-scope="scope">{{ scope.row.updateTime  }}</template>
                        </el-table-column>
                        <el-table-column prop="updateUserName" header-align="center" align="center" label="编辑人" />
                        <el-table-column header-align="center" align="center" width="150" label="操作">
                            <template slot-scope="scope">
                                <el-button v-permission="['sys:config:update']" type="text" size="small"
                                    @click="handleCreateSide(scope.row)">
                                    客户管理
                                </el-button>
                                <el-button v-permission="['sys:config:update']" type="text" size="small"
                                    @click="handleUpdateHouse(scope.row)">
                                    修改
                                </el-button>
                                <el-button v-permission="['sys:config:delete']" type="text" size="small" @click="deleteHandle(scope.row)">删除
                                </el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                </div>
            </div>

            <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        </div>

        <!-- tree新增修改 -->
        <add-or-update-tree v-if="addOrUpdateVisibletree" ref="addOrUpdatetree" @getList="handleFilter" @getTree="getTree" />
        <!-- 新增修改 -->
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @getList="handleFilter" />
        <!-- 侧面弹框 -->
        <side-dialog v-if="SideDialogVisible" ref="SideDialog"></side-dialog>

        <!-- //阅读量弹框  -->
        <!-- <el-dialog :visible.sync="dialogPvVisible" title="读取数据">
            <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
                <el-table-column prop="key" label="Channel" />
                <el-table-column prop="pv" label="Pv" />
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
            </span>
        </el-dialog> -->

    </div>
</template>

<script>

import { daleteHouseTree, getHouseList, daleteHouse } from '@/api/assets'// 请求数据
import { HouseExportExcel, downloadMock, HouseImportExcel } from '@/api/index'// 请求数据
import permission from '@/directive/permission/index.js' // 权限判断指令
import { houseState, houseType, houseFunction } from '@/utils/enum' //字典

import Pagination from '@/components/Pagination' // secondary package based on el-pagination 分页组件
import Tree from './components/tree' // 树形组件
import SideDialog from './components/SideDialog' //侧面弹框组件
import AddOrUpdateTree from './add-or-update-tree' // tree新增或者修改弹框
import AddOrUpdate from './add-or-update' // 新增或者修改弹框

import { parseTime } from '@/utils'



export default {
    name: 'LayoutTable',
    components: { Pagination, Tree, AddOrUpdate, AddOrUpdateTree, SideDialog },
    directives: { permission }, // 指令
    // 过滤 {{row.status | statusFilte}}
    // html代码中，{{}}中实现filters顺序是 {{参数 | filters函数 | filters函数 | ...}}
    // 后面可以多个filters函数，前面filters函数return的结果是后面filters函数的参数。
    // 并且可以在过滤函数后面加上（）里面加上其他的参数。如 filterTwo('同学')
    filters: {
        // statusFilter (status) {
        //     const statusMap = {
        //         published: 'success',
        //         draft: 'info',
        //         deleted: 'danger'
        //     }
        //     return statusMap[status]
        // },
        typeFilter (type) {
            return calendarTypeKeyValue[type]
        },
        houseStateFilter (status) {
            let map = houseState;
            return map[status]
        }
    },
    data () {
        return {
            screenState: true, // 筛选框是否展示下拉按钮
            formState: false, // 筛选框的 开合
            // 筛选框的 form 表单
            filtrateForm: {
                name: '',
                house_state: "",//房屋状态
                house_function: "",//房屋功能
            },
            rules: { // 表单验证
                type: [{ required: true, message: 'type is required', trigger: 'change' }],
                timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
                title: [{ required: true, message: 'title is required', trigger: 'blur' }]
            },
            dataListSelections: [], // 批量删除选中
            // 树形选择结果
            treeData: {
                id: '',
                name: '',
                depth: '',
                code: ''
            },
            tableKey: 0,
            list: [], // 表格数据
            total: 0, // 总条数
            listLoading: true, // 表格加载数据时的 loading
            listQuery: { // 表格当前页 和 当前页的展示数量
                page: 1,
                limit: 20
            },
            addOrUpdateVisibletree: false, // 楼栋 新增和修改 弹框展示隐藏
            addOrUpdateVisible: false,
            SideDialogVisible: false,


            // dialogPvVisible: false, //阅读量弹框
            // pvData: [], //阅读量弹框里面的表格数据
            downloadLoading: false, // 导出按钮 的 loading
            downloadLoading1: false, // 下载模板 的 loading
            action: HouseImportExcel(),//导入地址
            headers: {},//导入参数
        }
    },
    computed: {
        houseState_ () {
            let arr = [{ lable: '全部', value: '' }]
            for (let key in houseState) {
                arr.push({
                    lable: houseState[key],
                    value: key
                })
            }
            return arr
        },
        houseFunction_ () {
            let arr = [{ lable: '全部', value: '' }]
            for (let key in houseFunction) {
                arr.push({
                    lable: houseFunction[key],
                    value: key
                })
            }
            return arr
        }
    },
    created () {
        this.getList()
    },
    methods: {
        // 树选择
        setTreeData (data) {
            console.log('树形选择结果', data)
            this.treeData.id = data.id
            this.treeData.parkId = data.parkId
            this.treeData.type = data.type
            // this.treeData.name = data.name
            // this.treeData.depth = data.depth
            // this.treeData.code = data.code
            this.handleFilter()
        },

        // 获取表格数据
        async getList () {
            this.listLoading = true
            let tree_params = {
                '0': {
                    parkId: this.treeData.parkId
                },
                '1': {
                    buildingId: this.treeData.id
                },
                '2': {
                    unitId: this.treeData.id
                },
                '3': {
                    floorId: this.treeData.id
                }
            }
            // 筛选+分页
            const params = Object.assign({
                houseName: this.filtrateForm.name,
                houseState: this.filtrateForm.house_state,
                houseType: this.filtrateForm.house_function
            }, tree_params[this.treeData.type], this.listQuery)
            // 请求
            const res = await getHouseList(params).catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            console.log(data)

            this.list = data.list
            this.total = data.totalCount
            this.listLoading = false
        },
        // 重新获取表格数据 页码归为1
        handleFilter () {
            this.listQuery.page = 1
            this.getList()
        },
        //刷新tree
        getTree () {
            this.$refs.tree.getTree()
        },
        go_menu (e) {
            if (['delete_building', 'delete_unit', 'delete_floor'].includes(e.type)) {
                this.handleDeleteTree(e.node)
            }
            if (['add_building', 'add_unit', 'add_floor'].includes(e.type)) {
                this.handleCreate(e.node)
            }
            if (['up_building', 'up_unit', 'up_floor'].includes(e.type)) {
                this.handleUpdate(e.node)
            }
        },
        // Tree新增数据-打开弹框
        handleCreate (param) {
            this.addOrUpdateVisibletree = true
            // let param = param
            this.$nextTick(() => {
                this.$refs.addOrUpdatetree.init('create', param)
            })
        },
        // Tree修改 -- 打开弹框
        handleUpdate (row) {
            this.addOrUpdateVisibletree = true
            this.$nextTick(() => {
                this.$refs.addOrUpdatetree.init('update', row)
            })
        },
        //删除tree
        async handleDeleteTree (data) {
            // let param = {
            //     id: data.id
            // }
            this.$confirm(`确定对[${data.storeyName}]进行[删除]操作?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 提交删除
                const { code, message } = await daleteHouseTree({}, data.id)
                // 成功
                this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                        this.handleFilter()// 刷新数据
                        this.getTree()
                    }
                })
            })
        },
        // 新增数据-打开弹框
        handleCreateSide (param) {
            this.SideDialogVisible = true
            // let param = param
            this.$nextTick(() => {
                this.$refs.SideDialog.init('客户信息管理', param)
            })
        },
        // 新增数据-打开弹框
        handleCreateHouse (param) {
            this.addOrUpdateVisible = true
            // let param = param
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init('create', param)
            })
        },
        // 修改 -- 打开弹框
        handleUpdateHouse (row) {
            this.addOrUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init('update', row)
            })
        },
        // 批量删除数据 - 多选
        selectionChangeHandle (val) {
            this.dataListSelections = val
        },
        // 删除数据
        deleteHandle (data) {
            const idS = data ? [data.id] : this.dataListSelections.map(item => { return item.id })
            const nameS = data ? [data.name] : this.dataListSelections.map(item => { return item.name })
            this.$confirm(`确定对[${nameS.join('、')}]进行[删除]操作?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 提交删除
                const { code, message } = await daleteHouse({}, idS)
                // 成功
                this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                        this.handleFilter()// 刷新数据
                    }
                })
            })
        },
        //导入成功
        handleSuccess (data, file, fileList) {
            if (data && data.code === 200) {
                this.$message({
                    message: "操作成功",
                    type: "success",
                    duration: 1500,
                    onClose: () => {
                        this.handleFilter()// 刷新数据
                    }
                });
            } else {
                this.$message.error(data.message);
            }
        },
        //下载模板
        handleDownloadMock () {
            this.downloadLoading1 = true
            // let params = `?&page=${this.listQuery.page}&limit=${this.listQuery.limit}`
            // const url = `${process.env.VUE_APP_BASE_API}/assets/house/exportExcel${params}`
            const url = downloadMock('房屋导入模板.xls')
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            // link.setAttribute('download', 'xxx.xlsx');
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)

            this.downloadLoading1 = false
        },
        //导出 后台接口
        handleDownload () {
            this.downloadLoading = true
            // let params = `?&page=${this.listQuery.page}&limit=${this.listQuery.limit}`
            // const url = `${process.env.VUE_APP_BASE_API}/assets/house/exportExcel${params}`
            const url = HouseExportExcel(this.listQuery)
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            // link.setAttribute('download', 'xxx.xlsx');
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            this.downloadLoading = false
        },

    }
}
</script>
<style lang="scss" scoped>
//表格布局的注释：
//$rowLength 这个变量表示了 筛选的搜索框会有多少行，由于在不同宽度显示器下 所占行数会不一定 ，所以下面使用媒体查询 做兼容
//最小兼容至 1366
@import '~@/styles/layout-table.scss';
$rowLength: 2;
@media all and (min-width: 1659px) {
    $rowLength: 1;
    @include calculation($rowLength: $rowLength);
}
@media all and (max-width: 1659px) {
    $rowLength: 1;
    @include calculation($rowLength: $rowLength);
}
</style>
